/**
 * PackageDir: info.javafans.cdn.database
 * FileName: DbHelper.java
 * CreateDate: 2011-3-3 下午07:35:46
 * Copyright: Copyright (c) 2011 <br />
 * Company: fossd <br />
 * @author Yintao Xue
 * @version 1.0 2011-3-3
 */
package info.javafans.cdn.database;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.log4j.Logger;

/**
 * 数据库库查询帮助类 Project: CollegeDatingNetwork <br />
 * ClassName: DbHelper <br />
 * Description: <br />
 */
public class DbHelper {
	private static ConnectionPool connectionPool = ConnectionPool.getInstance();
	private static QueryRunner queryRunner = new QueryRunner();
	private static Logger logger = Logger.getLogger(DbHelper.class);

	/**
	 * 获取数据库连接
	 * 
	 * @return
	 */
	public static Connection getConnection() {
		return connectionPool.getConnection();
	}

	/**
	 * 读取单个对象 queryBean
	 * 
	 * @param <T>
	 * @param beanClass
	 * @param sql
	 * @param params
	 * @return
	 * @throws SQLException
	 */
	public static <T> T queryBean(Class<T> beanClass, String sql, Object... params) {
		try {
			return (T) queryRunner.query(getConnection(), sql, new BeanHandler(beanClass), params);
		} catch (SQLException e) {
			logger.error(e.getMessage());
			return null;
		}
	}

	/**
	 * 查询对象List queryBeanList
	 * 
	 * @param <T>
	 * @param beanClass
	 * @param sql
	 * @param params
	 * @return
	 * @throws SQLException
	 */
	public static <T> List<T> queryBeanList(Class<T> beanClass, String sql, Object... params) {
		try {
			return (List<T>) queryRunner.query(getConnection(), sql, new BeanListHandler(beanClass), params);
		} catch (SQLException e) {
			logger.error(e.getMessage());
			return null;
		}
	}
	
	 /**  
     * 执行INSERT/UPDATE/DELETE语句  
     * @param sql  
     * @param params  
     * @return  
     */  
    public static int update(String sql, Object...params) {   
        try{   
            return queryRunner.update(getConnection(), sql, params);   
        }catch(SQLException e){   
        	logger.error(e.getMessage());
			return -1;
        }   
    }   


}